<template>
  <div class="job-list">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item label="职位名称" prop="jobName">
            <el-input v-model="searchForm.jobName" placeholder="请输入职位名称"></el-input>
          </el-form-item>
          <el-form-item label="职位类别" prop="categoryId">
            <el-select v-model="searchForm.categoryId" placeholder="请选择职位类别" clearable>
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="jobName" label="职位名称"></el-table-column>
        <el-table-column prop="categoryName" label="职位类别"></el-table-column>
        <el-table-column prop="employerName" label="发布单位"></el-table-column>
        <el-table-column prop="demandNumber" label="需求人数"></el-table-column>
        <el-table-column prop="hiredNumber" label="已录用人数"></el-table-column>
        <el-table-column prop="remark" label="职位描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.row)"
              title="删除">
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AdminJobList',
  data() {
    return {
      loading: false,
      searchForm: {
        jobName: '',
        categoryId: null,
        employerId: null
      },
      categoryOptions: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      categoryMap: {},
      employerMap: {}
    }
  },
  created() {
    this.fetchData()
    this.getCategoryOptions()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const response = await this.$http.post('/job/page1', {
          current: this.currentPage,
          size: this.pageSize,
          ...this.searchForm
        })
        if (response.data.code === 200) {
          const records = response.data.data.records
          const employerIds = [...new Set(records.map(item => item.employerId))]
          await this.getEmployersByIds(employerIds)
          
          this.tableData = records.map(item => ({
            ...item,
            categoryName: this.categoryMap[item.categoryId] || '未知类别',
            employerName: this.employerMap[item.employerId] || '未知单位'
          }))
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取职位列表失败')
        }
      } catch (error) {
        console.error('获取职位列表失败:', error)
        this.$message.error('获取职位列表失败')
      } finally {
        this.loading = false
      }
    },
    async getEmployersByIds(employerIds) {
      try {
        const requests = employerIds.map(id => 
          this.$http.get(`/employer/${id}`)
            .then(response => {
              if (response.data.code === 200) {
                this.employerMap[id] = response.data.data.employerName
              }
            })
            .catch(error => {
              console.error(`获取用人单位(ID: ${id})信息失败:`, error)
            })
        )
        await Promise.all(requests)
      } catch (error) {
        console.error('获取用人单位信息失败:', error)
      }
    },
    async getCategoryOptions() {
      try {
        const response = await this.$http.get('/job-category/list')
        if (response.data.code === 200) {
          this.categoryOptions = response.data.data
          this.categoryMap = this.categoryOptions.reduce((map, item) => {
            map[item.id] = item.categoryName
            return map
          }, {})
        }
      } catch (error) {
        console.error('获取职位类别失败:', error)
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该职位?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.post(`/job/delete/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        } else {
          this.$message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.job-list {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 